package chooongg.base.manager

import android.annotation.SuppressLint
import android.content.Context
import chooongg.base.BaseApplication

inline val app get() = AppManager.getApp()

object AppManager {

    private var app: BaseApplication? = null

    fun init(context: Context) {
        init(context as BaseApplication)
    }

    fun init(application: BaseApplication) {
        if (app == null) {
            app = application
            NetworkManager.init(application)
        } else {
            throw RuntimeException("AppManager只能初始化一次")
        }
    }

    fun getApp(): BaseApplication {
        if (app != null) return app as BaseApplication
        return try {
            @SuppressLint("PrivateApi")
            val activityThread = Class.forName("android.app.ActivityThread")
            val at = activityThread.getMethod("currentActivityThread").invoke(null)
            val app = activityThread.getMethod("getApplication").invoke(at)
                    ?: NullPointerException("你需要在Manifest中注册")
            init(app as BaseApplication)
            app
        } catch (e: Exception) {
            throw NullPointerException("AppManager需要初始化")
        }
    }
}